<?php
/*
 * Copyright (C) 2009 Jeffrey Palm
 */

echo '<p>';
echo '<form method="get" action="' . phpSelf() . '">';
echo '<input type="text" id="q" name="q" value="' . $_REQUEST['q'] . '" length="50" />';
echo '<input type="submit" value="Search" />';
echo '</form>';

if (!isset($_REQUEST['q'])) {
  echo '<p>';
  echo 'Please type is a search term and click <em>Search</em> to search ' . TITLE;
  echo '</p>';
  return;
 }

$q = $_REQUEST['q'];
$events = readEvents('data.xml');

class SearchResult {
  function SearchResult($event,$score) {
    $this->event = $event;
    $this->score = $score;
  }
  function getEvent() { return $this->event; }
  function getScore() { return $this->score; }
}

class SearchResultList {
  function SearchResult() {
    $this->events = array();
    $this->score = 0;
  }
  function addResult($sr) {
    $this->events []= $sr->getEvent();
    $this->score += $sr->getScore();
  }
  function getEvents() { return $this->events; }
  function getScore() { return $this->score; }
}


$searchResults = array();
foreach ($events as $e) {
  $score = 0;
  $regex = '/' . strtolower($q) . '/';
  $score += preg_match($regex,strtolower($e->getTitle()));
  $score += preg_match($regex,strtolower($e->getDay()));
  $score += preg_match($regex,strtolower($e->getType()));
  $score += preg_match($regex,strtolower($e->getAddress()));
  if ($score == 0) continue;
  $searchResults []= new SearchResult($e,$score);
}

// Put all the results
$names2searchResultLists = array();
foreach ($searchResults as $sr) {
  $e = $sr->getEvent();
  $name = $e->getTitle();
  $srl = $names2searchResultLists[$name];
  if (!$srl) $srl = new SearchResultList();
  $srl->addResult($sr);
  $names2searchResultLists[$name] = $srl;
}

function searchResultListCompare($a,$b) {
  return $b->getScore() - $a->getScore();
}
$searchResultLists = array_values($names2searchResultLists);
usort($searchResultLists,'searchResultListCompare');

$numResults = count($searchResultLists);
$numMatches = count($searchResults);
echo '<p>';
echo '<b>Yippee!</b> We found ' . $numResults . ' location';
if ($numResults != 1) echo 's';
echo ' with ' . $numMatches . ' match';
if ($numMatches != 1) echo 's';
echo '.';
echo '</p>';

echo '<p>';
echo '<ol>';
$i = 1;
foreach ($searchResultLists as $srl) {
  echo '<li>';
  $id = '_id_' . ($i++);
  printEvents($srl->getEvents(),$id);
  echo '</li>';
}
echo '</ol>';
echo '</p>';


?>